/**
 * 快速检索
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, DatePicker, Select, Tooltip, Icon, message } from 'antd';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import { Const } from '../../Const';
import {
  listUnderchargeLuggageQuick
} from '../service';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

const QuickRetrievalPopup = props => {

  const { modalVisible, onCancel, form, onSubmit, ownerType, selectCityData } = props;

  const [createStartTime, setCreateStartTime] = useState(''); // 开始时间
  const [createEndTime, setCreateEndTime] = useState(''); // 结束时间

  // 快速检索列表
  const { run: runListUnderchargeLuggageQuick } = useRequest(params => listUnderchargeLuggageQuick(params), {
    manual: true,
    onSuccess (res, obj) {
      console.log(res, obj, '快速检索列表');
      let arr = res?.data || [];
      if (arr.length === 0) {
        message.warning('没有查询到数据');
      } else {
        onSubmit();
        router.push({
          pathname: Const.commonUrl + '/quickRetrieval',
          state: {
            ownerType,
            searchData: obj[0]
          }
        });
      }
    }
  })

  // 禁用今天之后的时间
  const disabledDate = useCallback((current) => {
    return current && current > moment().endOf('day');
  }, []);

  const disabledStartDate = useCallback((current) => {
    if (createEndTime) return current && (current > moment().endOf('day') || current > moment(createEndTime).endOf('day'));
    return current && current > moment().endOf('day');
  }, [createEndTime]);

  const disabledEndDate = useCallback((current) => {
    if (createStartTime) return current && (current > moment().endOf('day') || current < moment(createStartTime).startOf('day'));
    return current && current > moment().endOf('day');
  }, [createStartTime]);

  // 确定
  const okHandle = useCallback(() => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log(fieldsValue, 'fieldsValue')
      // form.resetFields();
      let obj = {};
      for (let key in fieldsValue) {
        if (key === 'flightDate' || key === 'startTime' || key === 'endTime') {
          if (fieldsValue[key] && fieldsValue[key].isValid()) {
            obj[key] = moment(fieldsValue[key]).format(Const.format);
            continue;
          }
        }
        if (!!fieldsValue[key]) {
          obj[key] = fieldsValue[key];
          continue;
        }
      }
      if ((fieldsValue.startTime && !fieldsValue.endTime) || (!fieldsValue.startTime && fieldsValue.endTime)) {
        message.warning('开始时间和结束时间必须同时选择');
      } else {
        runListUnderchargeLuggageQuick(obj);
      }
    });
  }, [form]);

  // 证件号 - 校验
  const idNoValidator = useCallback((rule, value, callback) => {
    if (!value) {
      if (!form.getFieldValue('tktNo') && !form.getFieldValue('pkgNo')) {
        callback('客票号、行李牌号、证件号必填一项，请补充查询条件');
      } else {
        callback();
      }
    } else {
      callback();
    }
  }, [form]);
  // 客票号 - 校验
  const tktNoValidator = useCallback((rule, value, callback) => {
    if (value) {
      callback();
    } else {
      if (!form.getFieldValue('idNo') && !form.getFieldValue('pkgNo')) {
        callback('客票号、行李牌号、证件号必填一项，请补充查询条件');
      } else {
        callback();
      }
    }
  }, [form]);
  // 行李号 - 校验
  const pkgNoValidator = useCallback((rule, value, callback) => {
    if (value) {
      callback();
    } else {
      if (!form.getFieldValue('idNo') && !form.getFieldValue('tktNo')) {
        callback('客票号、行李牌号、证件号必填一项，请补充查询条件');
      } else {
        callback();
      }
    }
  }, [form]);
  // 航班日期 - 校验
  const flightDateValidator = useCallback((rule, value, callback) => {
    let startTime = form.getFieldValue('startTime');
    let endTime = form.getFieldValue('endTime');
    if (value && (startTime || endTime)) {
      callback('航班日期、开始时间、结束时间不能同时存在');
    } else {
      callback();
    }
  }, [form]);
  // 时间 - 校验
  const startTimeValidator = useCallback((rule, value, callback) => {
    let flightDate = form.getFieldValue('flightDate');
    let endTime = form.getFieldValue('endTime');
    if (value) {
      if (flightDate) {
        callback('航班日期、开始时间、结束时间不能同时存在');
      } else if (!endTime) {
        callback('开始时间、结束时间必须同时存在');
      } else {
        callback();
      }
    } else {
      callback();
    }
  }, [form]);
  const endTimeValidator = useCallback((rule, value, callback) => {
    let flightDate = form.getFieldValue('flightDate');
    let startTime = form.getFieldValue('startTime');
    if (value) {
      if (flightDate) {
        callback('航班日期、开始时间、结束时间不能同时存在');
      } else if (!startTime) {
        callback('开始时间、结束时间必须同时存在');
      } else {
        callback();
      }
    } else {
      callback();
    }
  }, [form]);

  return (
    <Modal
      destroyOnClose
      title="快速检索"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="航班号">
          {form.getFieldDecorator('flightNo', {
            rules: [],
            initialValue: ''
          })(
            <Input
              placeholder="请输入"
              suffix={
                <Tooltip title="例AA123、AA1234、AA123A、AA1234A、MF8943A、3U234">
                  <Icon type="question-circle" style={{ color: Const.tooltipColor }} />
                </Tooltip>
              }
              onChange= {e => {
                let val = Const.formatFlightNo(e.target.value);
                setTimeout(() => {
                  form.setFieldsValue({
                    flightNo: val
                  })
                }, 0)
              }}
              maxLength={6}
              placeholder="3U"
            />
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="航班日期">
          {form.getFieldDecorator('flightDate', {
            rules: [
              { validator: flightDateValidator }
            ],
            initialValue: moment()
          })(<DatePicker format={Const.format} placeholder="请选择日期" disabledDate={disabledDate} style={{ width: '100%' }} />)}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="证件类型">
          {form.getFieldDecorator('idType', {
            rules: [],
            initialValue: ''
          })(
            <Select style={{ width: '100%' }} allowClear>
              {Const.idTypeListForSearch.map(item => (
                <Option key={item.value}>{item.label}</Option>
              ))}
            </Select>
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="证件号">
          {form.getFieldDecorator('idNo', {
            rules: [
              { validator: idNoValidator }
            ],
            initialValue: ''
          })(<Input placeholder="请输入" maxLength={18} />)}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="客票号">
          {form.getFieldDecorator('tktNo', {
            rules: [
              { pattern: /^\d{13}$/, message: '请输入13位数字' },
              { validator: tktNoValidator }
            ],
            initialValue: ''
          })(<Input placeholder="请输入" maxLength={13} />)}
        </FormItem>
        <FormItem {...Const.formLayout} label="行李号">
          {form.getFieldDecorator('pkgNo', {
            rules: [
              { pattern: /^([A-Z\d]{6}|[A-Z\d]{8}|[A-Z\d]{10})$/, message: '行李号不正确，正确格式如123456、AA123456、1234567890' },
              { validator: pkgNoValidator }
            ],
            initialValue: ''
          })(
            <Input
              placeholder="请输入"
              suffix={
                <Tooltip title="例123456、AA123456、1234567890">
                  <Icon type="question-circle" style={{ color: Const.tooltipColor }} />
                </Tooltip>
              }
              maxLength={10}
            />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="始发地">
          {form.getFieldDecorator('orgPlace', {
            rules: [],
            initialValue: ''
          })(
            <Select
              allowClear
              showSearch
              placeholder="请选择"
              optionFilterProp="children"
              style={{ width: '100%' }}
            >
              {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
            </Select>
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="目的地">
          {form.getFieldDecorator('dstPlace', {
            rules: [],
            initialValue: ''
          })(
            <Select
              allowClear
              showSearch
              placeholder="请选择"
              optionFilterProp="children"
              style={{ width: '100%' }}
            >
              {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
            </Select>
          )}
        </FormItem>
      </div>
      <div className={styles.formContentTwo}>
        <FormItem {...Const.formLayout} label="开始时间">
          {form.getFieldDecorator('startTime', {
            rules: [
              { validator: startTimeValidator }
            ]
          })(
            <DatePicker
              format={Const.format}
              placeholder="请选择日期"
              onChange={val => {
                setCreateStartTime(val);
                // setTimeout(() => {
                //   form.setFieldsValue({
                //     startTime: val
                //   })
                // }, 0);
              }}
              disabledDate={disabledStartDate}
              style={{ width: '100%' }} />
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="结束时间">
          {form.getFieldDecorator('endTime', {
            rules: [
              { validator: endTimeValidator }
            ]
          })(
            <DatePicker
              format={Const.format}
              placeholder="请选择日期"
              onChange={val => {
                setCreateStartTime(val);
                // setTimeout(() => {
                //   form.setFieldsValue({
                //     endTime: val
                //   })
                // }, 0);
              }}
              disabledDate={disabledEndDate}
              style={{ width: '100%' }} />
          )}
        </FormItem>
      </div>
    </Modal>
  )
};

export default Form.create()(QuickRetrievalPopup);
